<?php
header('Content-Type: text/plain');
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
session_name(SESSION);
session_start();
$myPdo = DbUtils::createPdoInst();
$action = $_POST['action'];
try {
  $myPdo->beginTransaction();
  switch ($action) {
    case 'del_product':
      del_product($myPdo);
      break;
    case 'update_available':
      update_available($myPdo);
      break;
    default:
      break;
  }
  $myPdo->commit();
} catch (PDOException $e) {
  echo $e->getMessage();
}

function update_available($myPdo) {
  if (!isset($_SESSION['admin' . USER])) {
    return;
  }
  $q = json_decode(MiscUtils::getParam('q', '[]'));
  DbUtils::update($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_product', $q);
  echo json_encode(array());
}

function del_product($myPdo) {
  if (!isset($_SESSION['admin' . USER])) {
    return;
  }
  $q = json_decode(MiscUtils::getParam('q', '[]'));
  
  $cond_vals = new stdClass();
  $cond_vals->c = 'product_track_id = :v1';
  $cond_vals->v = array(':v1' => $q);
  DbUtils::deleteByCond($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_product_member_price', $cond_vals);
  
  $cond_vals = new stdClass();
  $cond_vals->c = 'product_track_id = :v1';
  $cond_vals->v = array(':v1' => $q);
  DbUtils::deleteByCond($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_product_object', $cond_vals);

  $cond_vals = new stdClass();
  $cond_vals->c = 'product_track_id = :v1';
  $cond_vals->v = array(':v1' => $q);
  DbUtils::deleteByCond($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_product_attr', $cond_vals);
  
  $cond_vals = new stdClass();
  $cond_vals->c = 'product_track_id = :v1';
  $cond_vals->v = array(':v1' => $q);
  DbUtils::deleteByCond($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_product_attr_opt', $cond_vals);
  
  $cond_vals = new stdClass();
  $cond_vals->c = 'product_track_id = :v1';
  $cond_vals->v = array(':v1' => $q);
  $imgs = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_product_img', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
  foreach ($imgs as &$img) {
    $obj_path = iconv('UTF-8', 'GB2312', $img->file);
    if (file_exists($obj_path)) {
      @unlink($obj_path);
    }
  }
      
  $cond_vals = new stdClass();
  $cond_vals->c = 'product_track_id = :v1';
  $cond_vals->v = array(':v1' => $q);
  DbUtils::deleteByCond($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_product_img', $cond_vals);
  
  $cond_vals = new stdClass();
  $cond_vals->c = 'track_id = :v1';
  $cond_vals->v = array(':v1' => $q);
  DbUtils::deleteByCond($myPdo, TABLE_NAME_PREFIX_PLUGIN . 'ecom_product', $cond_vals);
  
  echo json_encode(array());
}

?>